/**
 * User: alesj
 * Date: 2005.3.25
 * Time: 12:06:59
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.ecos.page;

import java.util.List;

/**
 * @author Pietro Polsinelli ppolsinelli@open-lab.com
 * @author Ales Justin ales.justin@gmail.com
 */
public class ListPage extends AbstractPage {

    /**
     * Construct a new ListPage. ListPage numbers are zero-based, so the
     * first page is page 0.
     *
     * @param pageNumber the page number (zero-based); if Integer.MAX_VALUE will return the last page for the query
     * @param pageSize   the number of results to display on the page
     */
    public ListPage(List elements, int pageNumber, int pageSize) {
        super(pageNumber, pageSize);
        this.elements = elements;
        if (Integer.MAX_VALUE == this.pageNumber) {
            this.pageNumber = (getTotalNumberOfElements() / this.pageSize);
        }
    }

    public boolean hasNextPage() {
        return ((getPageNumber() + 1) * getPageSize()) < (getTotalNumberOfElements() + 1);
    }

    public List getThisPageElements() {
        /*
        * Since we retrieved one more than the specified pageSize when the
        * class was constructed, we now trim it down to the pageSize if a next
        * page exists.
        */
        final int start = getPageNumber() * getPageSize();
        return elements.subList(Math.min(start, getTotalNumberOfElements()),
                                Math.min(start + getPageSize(), getTotalNumberOfElements() + 1));
    }

    /**
     * this is 0-based, differently from list.size();
     */
    public int getTotalNumberOfElements() {
        return elements.size() - 1;
    }

}